package com.bsoft.gol.hcb.service;

import com.bsoft.gol.hcb.dao.PatientCollectDAO;
import ctd.account.UserRoleToken;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.BeanUtils;
import ctd.util.annotation.RpcService;
import ctd.util.converter.ConversionUtils;
import hcn.base.Dept;
import hcn.base.Organization;
import hcn.base.mch.CanDoOrNot;
import hcn.base.mch.CanEatOrNot;
import hcn.base.mch.qo.GetFoodKindsDetailQO;
import hcn.base.mch.qo.GetThingsDetailQO;
import hcn.common.CodeDefinition;
import hcn.ods.OdsPatientcollect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import pcn.enums.DoctorTitleEnum;
import service.rpc.*;
import com.bsoft.gol.hcb.utils.CommonUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created on 2021/8/17
 * 居民收藏医生记录管理
 *
 * @author Marvin Yang
 */
@SsdevService("patientCollectService")
public class PatientCollectService {

    @Autowired
    private PatientCollectDAO patientCollectDAO;
    @Autowired
    private DoctorInfoServiceIntf doctorInfoServiceIntf;
    @Autowired
    private DeptInfoServiceIntf deptInfoServiceIntf;
    @Autowired
    private OrganizationInfoIntf organizationInfoService;
    @Autowired
    private CanEatOrNotInfoService canEatOrNotInfoService;
    @Autowired
    private CanDoOrNotInfoService canDoOrNotInfoService;
    @Value("${project_source:GOL}")
    private String projectSource;

    /**
     * addPatientCollect 新增患者收藏记录
     *
     * @param userId, objectId, objectType
     * @return void
     * @throws
     * @Description:
     * @author chase
     * @date 2016/4/6
     */
    @RpcService
    public boolean createPatientCollect(String userId, String objectId, String objectType, String orgId, String regDeptId, String deptId) throws ControllerException {
        // TODO 保存时冗余必要的字段 review by cdw
        OdsPatientcollect pc = new OdsPatientcollect();
        pc.setObjectId(objectId);
        pc.setObjectType(objectType);
        pc.setUserId(userId);
        pc.setCreateDt(new Date());
        pc.setOrgId(orgId);
        pc.setRegDeptId(regDeptId);
        pc.setDeptId(deptId);
        try {
            patientCollectDAO.savePatientCollect(pc);
            return true;
        } catch (ControllerException e) {
            throw new ControllerException("save patient collect error," + e);
        }
    }


    /**
     * removePatientCollect 删除患者收藏医生记录
     *
     * @param userId, objectId, objectType
     * @return boolean
     * @throws
     * @Description:
     * @author chase
     * @date 2016/4/6
     */
    @RpcService
    public boolean removePatientCollect(String userId, String objectId, String objectType) throws ControllerException {
        OdsPatientcollect pc = new OdsPatientcollect();
        pc.setObjectId(objectId);
        pc.setObjectType(objectType);
        pc.setUserId(userId);
        try {
            patientCollectDAO.removePatientCollect(pc);
            return true;
        } catch (ControllerException e) {
            throw new ControllerException("remove patient collect error," + e);
        }
    }


    /**
     * findPatientCollect 根据objectType获取患者的收藏记录
     *
     * @param userId, objectType
     * @return hcn.ods.PatientCollect
     * @throws
     * @Description:
     * @author chase
     * @date 2016/4/6
     */
    @RpcService
    public List<OdsPatientcollect> getPatientCollectByObjectType(String userId, String objectType, int page, int limit) throws ControllerException {
        return patientCollectDAO.getPatientCollectByObjectType(userId, objectType, page, limit);
    }


    /**
     * getPatientCollectDetail
     *
     * @param userId, objectType
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @throws
     * @Description: 查询收藏管理
     * @author chase
     * @date 2016/7/21
     */
    @RpcService
    public List<Map<String, Object>> getPatientCollectDetail(String userId, String objectType, int page, int limit) throws ControllerException {
        List<OdsPatientcollect> collects = getPatientCollectByObjectType(userId, objectType, page, limit);
        if (collects == null || collects.isEmpty()) {
            return null;
        }
        List<String> orgIds = new ArrayList<>(16);
        collects.forEach(e -> {
            orgIds.add(e.getOrgId());
        });
        Map<String, Organization> resultMaps = new HashMap<>(16);
        try {
            List<Organization> organizationList = organizationInfoService.findOrganizationByOrgList(orgIds);
            resultMaps = organizationList.stream().collect(Collectors.toMap(Organization::getOrgId, organization -> organization));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        List<Map<String, Object>> list = new ArrayList<>();
        switch (objectType) {
            // TODO 定义枚举 review by cdw
            case "031":
                for (OdsPatientcollect patientcollect : collects) {
                    Map<String, Object> data = new HashMap<>();
                    if (CommonUtils.isNotEmpty(patientcollect.getDeptId())) {
                        data = doctorInfoServiceIntf.getDoctorOutOFline(patientcollect.getObjectId(), patientcollect.getDeptId());
                    } else {
                        if (CommonUtils.isNotEmpty(patientcollect.getObjectId())) {
                            data = doctorInfoServiceIntf.getDoctorOutline(patientcollect.getObjectId());
                        }
                    }
                    //患者如果收藏普通号，ObjectId 则会没有值，为了保证显示普通号，此处允许 ObjectId =null
                    if (data == null && CommonUtils.isNotEmpty(patientcollect.getObjectId())) {
                        continue;
                    }
                    Map map = ConversionUtils.convert(patientcollect, Map.class);
                    //collectionType 收藏类型，1：医生  2 ：科室(普通号)
                    if (CommonUtils.isNotEmpty(patientcollect.getObjectId())) {
                        map.put("collectionType", "1");
                    } else {
                        map.put("collectionType", "2");
                    }

                    //互联网医院预约挂号没有接入微服务,暂时关闭收藏中的跳转预约挂号入口
                    if ("HOL".equals(projectSource)) {
                        map.put("regFlag", false);
                    } else {
                        if (CommonUtils.isNotEmpty(map.get("regDeptId"))) {
                            map.put("regFlag", true);
                        } else {
                            map.put("regFlag", false);
                        }
                    }

                    if (CommonUtils.isNotEmpty(patientcollect.getDeptId())) {
                        Dept dept = deptInfoServiceIntf.getDeptByDeptId(patientcollect.getDeptId());
                        if (CommonUtils.isNotEmpty(dept)) {
                            map.put("deptName", dept.getName());
                        }
                    }
                    Organization organization = resultMaps.get(patientcollect.getOrgId());
//                    Organization organization = organizationInfoService.getOrgDetailByOrgId(patientcollect.getOrgId());
                    map.put("orgName", organization.getFullName());
                    if (CommonUtils.isNotEmpty(data) && CommonUtils.isNotEmpty(data.get("dlevel"))) {
                        map.put("dlevelText", DoctorTitleEnum.getContext(data.get("dlevel").toString()));
                    }
                    if (CommonUtils.isNotEmpty(data)) {
                        map.putAll(data);
                    }
                    list.add(map);
                }
                break;
            case "021":
                for (OdsPatientcollect patientcollect : collects) {
                    Map<String, Object> data = organizationInfoService.getOrgMainDetailById(patientcollect.getObjectId());
                    if (data == null) {
                        continue;
                    }
                    Map map = ConversionUtils.convert(patientcollect, Map.class);
                    map.putAll(data);
                    list.add(map);
                }
                break;
            case "061":
                for (OdsPatientcollect collect : collects) {
                    GetThingsDetailQO qo = new GetThingsDetailQO();
                    qo.setDoId(collect.getObjectId());
                    CanDoOrNot data = canDoOrNotInfoService.getThingsDetail(qo);
                    Map map = ConversionUtils.convert(collect, Map.class);
                    Map map1 = BeanUtils.map(data, Map.class);
                    map.putAll(map1);
                    list.add(map);
                }
                break;
            case "071":
                for (OdsPatientcollect collect : collects) {
                    GetFoodKindsDetailQO qo = new GetFoodKindsDetailQO();
                    qo.setEatId(collect.getObjectId());
                    CanEatOrNot data = canEatOrNotInfoService.getFoodKindsDetail(qo);
                    Map map = ConversionUtils.convert(collect, Map.class);
                    Map map1 = BeanUtils.map(data, Map.class);
                    map.putAll(map1);
                    list.add(map);
                }
                break;
            default:
                throw new ControllerException(CodeDefinition.INVENTORY_NOT_EXIST, "No such objectType:" + objectType);
        }
        return list;
    }


    @RpcService
    /**
     * findPatientCollect 根据objectType，objcetId获取患者的收藏记录
     * @Description:
     * @param [userId, objectType]
     * @return hcn.ods.PatientCollect
     * @throws
     * @author chase
     * @date 2016/4/6
     */
    public OdsPatientcollect getPatientCollectByObjectId(String userId, String objectId, String objectType) {
        String tenantId = UserRoleToken.getCurrentTenantId();
        return patientCollectDAO.getPatientCollectByObjectId(userId, objectId, objectType, tenantId);
    }

    @RpcService
    /**
     * findPatientCollect 获取患者的收藏记录
     * @Description:
     * @param [userId]
     * @return hcn.ods.PatientCollect
     * @throws
     * @author chase
     * @date 2016/4/6
     */
    public List<OdsPatientcollect> getPatientCollect(String userId, int page, int limit) {
        return patientCollectDAO.getPatientCollect(userId, page, limit);
    }

}
